let min = 0;
let max = 101;
let stu_data;
$(document).ready(function () {
    // 执行页面加载时获取学生列表
    getStudentList();

    // 监听修改学生信息表单提交事件
    $('.box1').submit(function (event) {
        event.preventDefault();
        let id = $('table .btn-danger').closest('tr').find('td:eq(0)').text();
        confirmEdit(id);
        $('.box1').css('visibility','hidden');
    });

    // 监听编辑按钮点击事件
    $('table').on('click', '.btn-primary', function () {
        let id = $(this).closest('tr').find('td:eq(0)').text();
        $('.box1').css('visibility','visible');
        editStudentInfo(id);
    });

    // 监听删除按钮点击事件
    $('table').on('click', '.btn-danger', function () {
        let id = $(this).closest('tr').find('td:eq(0)').text();
        deleteStudentInfo(id);
    });
    //监听清空学生表点击事件
    $('.tool').click(function () {
        clearStudent();
    });

    //监听搜索事件
    $('#search-button').on('click', function () {
        const keyName = $('#search-input').val();
        performSearch(keyName, min, max);
    });
});

// 获取学生成绩列表
function getStudentList() {
    $.ajax({
        url: "../api.php/get_student_grade",
        type: "GET",
        dataType: "json",
        // data:{'student_id': 10},
        success: function (res) {
            console.log('register', res);
            if (res["code"] === 200) {
                displayStudentList(res["data"]);
            }
        },
        error: function () {
            alert('出错了');
        }
    });
}

// 显示学生列表
function displayStudentList(data) {
    $('table tbody').empty();
    data.forEach(function (data) {

        $('table tbody').append(`
             <tr>
                  <td>${data.student_id}</td>
                  <td>${data.student_name}</td>
                  <td>${data.attendance}</td>
                  <td>${data.homework}</td>
                  <td>${data.quiz}</td>
                  <td>${data.interactive}</td>
                  <td>${data.midterm}</td>
                  <td>${data.final}</td>
                  <td>${data.total}</td>
                  <td>
                       <button type="button" class="btn btn-sm btn-primary">修改</button>                     
                  </td>
             </tr>
        `);
    });

}
//搜索逻辑

function performSearch(keyName, min, max) {
    min = 0;
    max = 101;
    if ($('#min').val() !== '')
        min = parseInt($('#min').val());
    if ($('#max').val() !== '')
        max = parseInt($('#max').val());

    if (keyName !== '' && max !== 101 || keyName !== '' && max === 101 && min > 0) {
        alert('姓名和区间不能同时输入！');
    } else if (keyName === '' && max === 101 && min === 0) {
        getStudentList();
    } else if (min > max) {
        alert('输入区间有误！');
        console.log(min);
        console.log(max);
    } else if (keyName !== '') {
        $.ajax({
            url: "../api.php/get_student_grade",
            type: "GET",
            dataType: "json",
            data: {'student_name': keyName, 'min': min, 'max': max},
            success: function (res) {
                if (res["code"] === 200) {
                    displayStudentList(res["data"]);
                }
            },
            error: function () {
                alert('出错了');
            }
        });
    } else {
        $.ajax({
            url: "../api.php/get_student_grade",
            type: "GET",
            dataType: "json",
            data: {'student_name': keyName, 'min': min, 'max': max},
            success: function (res) {
                if (res["code"] === 200) {
                    displayStudentList(res["data"]);
                }
            },
            error: function () {
                alert('出错了');
            }
        });
    }

}
// 编辑学生成绩
let needEditIndex = -1;
function editStudentInfo(id) {
    $.ajax({
        url: "../api.php/get_student_grade",
        type: "GET",
        dataType: "json",
        success: function (res) {
            console.log('register', res);
            if (res["code"] === 200) {
                needEditIndex = res["data"].findIndex(student => student.student_id === id);
                localStorage.setItem("stu_grades", JSON.stringify(res["data"]));
                try {
                    stu_data = JSON.parse(localStorage.getItem("stu_grades"));
                } catch (e) {
                    console.log(e);
                }
                document.getElementById("attendance_new").value = stu_data[needEditIndex].attendance;
                document.getElementById("homework_new").value = stu_data[needEditIndex].homework;
                document.getElementById("quiz_new").value = stu_data[needEditIndex].quiz;
                document.getElementById("interactive_new").value = stu_data[needEditIndex].interactive;
                document.getElementById("midterm_new").value = stu_data[needEditIndex].midterm;
                document.getElementById("final_new").value = stu_data[needEditIndex].final;
            }
        },
        error: function () {
            alert('出错了');
        }
    });
    // getStudentList();

}
//确认修改
function confirmEdit(id) {

    $.ajax({
        url: "../api.php/get_student_grade",
        type: "GET",
        dataType: "json",
        success: function (res) {
            if (res["code"] === 200) {
                let data = res.data;
                let student = {
                    student_id: data[needEditIndex].student_id,
                    attendance: data[needEditIndex].attendance,
                    homework: data[needEditIndex].homework,
                    quiz: data[needEditIndex].quiz,
                    interactive: data[needEditIndex].interactive,
                    midterm: data[needEditIndex].midterm,
                    final: data[needEditIndex].final
                };
                if ($('#attendance_new').val() != '')
                    student.attendance = $('#attendance_new').val();
                if ($('#homework_new').val() != '')
                    student.homework = $('#homework_new').val();
                if ($('#quiz_new').val() != '')
                    student.quiz = $('#quiz_new').val();
                if ($('#interactive_new').val() != '')
                    student.interactive = $('#interactive_new').val();
                if ($('#midterm_new').val() != '')
                    student.midterm = $('#midterm_new').val();
                if ($('#final_new').val() != '')
                    student.final = $('#final_new').val();

                $.ajax({
                    url: "../api.php/update_student_grade",
                    type: "POST",
                    dataType: "json",
                    data: {'student_id': student.student_id,'attendance': student.attendance, 'homework': student.homework, 'quiz':student.quiz, 'interactive': student.interactive,
                        'midterm': student.midterm,'final': student.final},
                    success: function (res) {
                        if (res["code"] === 200) {
                            alert('成功修改学生信息！');
                            location.reload();
                        }
                    },
                    error: function () {
                        alert('出错了');
                    }
                });
                getStudentList();
            }
        },
        error: function () {
            alert('出错了');
        }
    });


}

//清空数据
function clearStudent() {
    document.getElementById("attendance_new").value = "";
    document.getElementById("homework_new").value = "";
    document.getElementById("quiz_new").value = "";
    document.getElementById("interactive_new").value = "";
    document.getElementById("midterm_new").value = "";
    document.getElementById("final_new").value = "";

    // alert('数据清除成功！');
    // location.reload();
}
